<?php

namespace app\api\controller;

use addons\recharge\library\Order1;
use addons\recharge\model\MoneyLog;
use app\admin\model\free\Coupon;
use app\common\controller\Api;
use app\common\model\DeviceOrder;
use app\common\model\Device;
use app\common\model\Ground;
use app\common\model\GroundChild;
use app\common\model\User;
use app\common\model\DeviceRefind;
use think\Db;
use think\Exception;
use addons\epay\library\Service;
use Yansongda\Pay\Pay;

/**
 * 充值
 */
class Order extends Api
{
    protected $noNeedLogin = ['epay'];
    protected $noNeedRight = ['*'];


    /**
     * 订单列表
     * @return void
     */
    public function list()
    {
        $list = DeviceOrder::with('device,ground')
            ->where('device_order.user_id', $this->auth->id)
            ->where('device_order.status', 'paid')
            ->order('device_order.id desc')->paginate()->each(function ($item){
                $item['createtime'] = date('Y-m-d H:i:s',$item['createtime']);
                return $item;
            });
        $this->success('查询成功', $list);
    }

    /**
     * 订单详情接口
     * @return void
     * @throws \think\exception\DbException
     */
    public function orderDetails()
    {
        $id = $this->request->post('orderid');
        $list = DeviceOrder::with('device,ground')
            ->where('device_order.orderid', $id)->find();
        $this->success('查询成功', $list);
    }

    /**
     * 获取代理/商家订单
     * @return void
     */
    public function getAgentOrder()
    {
        $where = [];
        $orderid = $this->request->post('orderid');
        $start_time = $this->request->post('start_time');
        $end_time = $this->request->post('end_time');
        if (!empty($start_time) && !empty($end_time)) {
            $where['device_order.createtime'] = ['between', [strtotime($start_time), strtotime($end_time.' 23:59:59')]];
        }
        if (!empty($orderid)) {
            $where['device_order.orderid'] = ['like', '%' . $orderid . '%'];
        }
         //查询此商家所有场地
        $user_group = Ground::where('user_id',$this->auth->id)->column('id');
        //查询此商家所有场地
        $ground_ids = GroundChild::where('user_id',$this->auth->id)->column('ground_id');
        if(!$ground_ids){
            $ground_ids = [-1];
        }
        $where['device_order.ground_id'] = ['in',array_merge($ground_ids,$user_group)];
//        $where['device.user_id'] = $this->auth->id;
        $where['device_order.is_gifts'] = 0;
        $where['device_order.status'] = 'paid';
        $list = DeviceOrder::with('device,ground')
            ->where($where)
            ->order('device_order.id desc')->paginate()->each(function ($item){
                //查询此用户收益了多少
//                $item['shouyi'] = MoneyLog::where('order_id',$item['id'])->sum('money');
                $item['shouyi'] = MoneyLog::where('order_id',$item['id'])->where('user_id',$this->auth->id)->sum('money');
                return $item;
            });
        $this->success('查询成功', $list);
    }

    //更新订单
    public function updateOrder()
    {
        $yc_time = $this->request->post('yc_time');
        $id = $this->request->post('id');
        if ($yc_time) {
            $data = [
                'yc_time' => $yc_time,
                'updatetime' => time()
            ];
            $res = DeviceOrder::where('id', $id)->update($data);
            if ($res) {
                $this->success('修改成功');
            } else {
                $this->error('修改失败');
            }
        } else {
            $this->error('参数错误');
        }
    }


    public function refind()
    {
        $order_id = $this->request->post('order_id');
        $price = $this->request->post('price');
        if ($order_id) {
            //查询是否已存在
            $refind = DeviceRefind::where('order_id', $order_id)->find();
            if ($refind) {
                $this->error('已存在退款申请');
            }
            $order = DeviceOrder::find($order_id);
            //查询当前订单场地是否属于本用户
            if ($order->ground->user_id != $this->auth->id) {
                $this->error('订单不属于此用户');
            }
            //查询退款金额是否大于订单金额
            if ($price > $order->amount) {
                $this->error('退款金额不能大于订单金额');
            }
            //查询此订单所有收益
            $money_log = MoneyLog::where('order_id', $order_id)->where('memo','设备佣金结算')->select();
            $is_true = true;
            foreach ($money_log as $k => $v){
                $user = User::find($v['user_id']);
                if($user->money < $v['money']){
                    $is_true = false;
                }
            }
            if (!$is_true){
                $this->error('退款失败，请联系管理员');
            }

            if ($order) {
                Db::startTrans();
                try {
                    $refind = new DeviceRefind();
                    $refind->order_id = $order_id;
                    $refind->ground_id = $order->ground_id;
                    $refind->device_id = $order->device_id;
                    $refind->user_id = $order->user_id;
                    $refind->price = $price;
                    $refind->save();
                    if($order->paytype = 'wechat'){
                        $payData = [
                            'out_trade_no' => $order->orderid,
                            'out_refund_no' => time(),
                            'total_fee' => $order->payamount * 100,
                            'refund_fee' => $price * 100,
                            'refund_desc' => '订单退款',
                        ];
                        $config = Service::getConfig();
                        $result = Pay::wechat($config)->refund($payData);

                    }else{
                        $price = $price - $order->gifts_money;
                        if($price > 0){
                            User::money($price,$order->user_id, '订单退款', $order->ground_id, $order->device_id, $order->id);
                        }
                        if($order->gifts_money > 0){
                            User::gifts_money($order->gifts_money,$order->user_id, '订单退款', $order->ground_id, $order->device_id, $order->id);
                        }
                    }
                    foreach ($money_log as $k => $v){
                        User::money($v['money'],$v['user_id'], '订单退款回收佣金', $order->ground_id, $order->device_id, $order->id);
                    }
                    Db::commit();
                }catch (Exception $e){
                    Db::rollback();
                    $this->error('退款失败');
                }
                $this->success('退款成功');
            } else {
                $this->error('订单不存在');
            }
        } else {
            $this->error('参数错误');
        }
    }

    /**
     * 获取设备信息
     * @return void
     */
    public function getDeviceInfo()
    {
        $id = $this->request->post('id');
        $device = Device::with('ground')->where('device.name', $id)->find();
        $this->success('查询成功', $device);
    }



    /**
     * 创建订单并发起支付请求
     */
    public function submit()
    {

        $info = get_addon_info('epay');
        if (!$info || !$info['state']) {
            $this->error('请在后台插件管理安装微信支付宝整合插件后重试');
        }
        $device_id = $this->request->post('device_id');
        $ground_id = $this->request->post('ground_id');
        $type = $this->request->post('type');
        $yd_time = $this->request->post('yd_time');
        $amount = $this->request->post('amount');
        $paytype = $this->request->post('paytype');



        try {
            $device = Device::where('id', $device_id)->find();
            //查询设备状态
            if ($device->type == 'offline') {
                $this->error('设备已离线');
            }
            $orderid = date("Ymdhis") . sprintf("%02d", $this->auth->id) . mt_rand(1000, 9999);
            $data = [
                'orderid'   => $orderid,
                'user_id'   => $this->auth->id,
                'device_id' => $device_id,
                'ground_id' => $ground_id,
                'type'      => $type,
                'yd_time'   => $yd_time,
                'amount'    => $amount,
                'payamount' => 0,
                'paytype'   => $paytype,
                'status'    => 'created'
            ];
            $order = DeviceOrder::create($data);
            //查询余额是否充足
            $user = User::get($this->auth->id);
            if($paytype == 'money'){//如果余额支付，直接回调

                if($user->money+$user->gifts_money < $amount){
                    $this->error('余额不足');
                }
                if($user->money >= $amount){
                    User::money(-$amount,$user->id,  '余额支付');
                }else{
                    $gifts_money = $amount - $user->money;
                    if($user->money > 0){
                        User::money(-$user->money,$user->id,  '余额支付');
                    }
                    User::gifts_money(-$gifts_money,$user->id,  '余额支付');
                    $order->gifts_money = $gifts_money;
                    $order->is_gifts = 1;
                    $order->save();
                }

                //直接回调
                DeviceOrder::settle($orderid, $amount, '余额支付');
                $this->success('下单成功',$order);
            }elseif($paytype == 'free_coupon'){ // 使用免单券

                // 获取过期时间最早的免单券
                $coupon_id = Coupon::where('user_id', $this->auth->id)->where('status', 'created')->where('expiration_time', '>', time())->order('id', 'asc')->value('id');
                if($coupon_id == null) {
                    $this->error('免单券不可用');
                }
                try {
                    Coupon::update([
                        'status' => 'paid',
                        'order_id' => $orderid
                    ],[
                        'id' => ['=', $coupon_id]
                    ]);

                }catch (Exception $e) {
                    $this->error('免单券不可用');
                }

                $order->is_free = 1;
                $order->save();
                //直接回调
                DeviceOrder::settle($orderid, $amount, '免单券支付');
                $this->success('下单成功',$order);
            }else{
                $request = \think\Request::instance();
                $notifyurl = $request->root(true) . '/api/order/epay/type/notify/paytype/' . $paytype;
                $returnurl =  $request->root(true) . '/index/recharge/epay/type/return/paytype/' . $paytype;

                $params = [
                    'amount'    => $amount,
                    'orderid'   => $order->orderid,
                    'type'      => $paytype,
                    'title'     => "下单{$yd_time}分钟套餐",
                    'notifyurl' => $notifyurl,
                    'returnurl' => $returnurl,
                    'method'    => 'miniapp',
                    'openid'    => $user->openid
                ];

//                //微信小程序或公众号支付
//                if (!$openid && in_array($method, ['mp', 'miniapp'])) {
//                    throw new Exception("公众号和小程序支付openid不能为空！");
//                }

                $response = \addons\epay\library\Service::submitOrder($params);
                $response['order'] = $order;
            }
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('查询成功', $response);
    }

    /**
     * 支付订单
     * @return void
     */
    public function pay()
    {
        $id = $this->request->post('id');
        $order = DeviceOrder::get($id);
        $paytype = $order->paytype;
        $request = \think\Request::instance();
        $notifyurl = $request->root(true) . '/api/order/epay/type/notify/paytype/' . $paytype;
        $returnurl =  $request->root(true) . '/index/order/epay/type/return/paytype/' . $paytype;

        $params = [
            'amount'    => $order->amount,
            'orderid'   => $order->orderid,
            'type'      => $paytype,
            'title'     => "下单{$order->yd_time}分钟套餐",
            'notifyurl' => $notifyurl,
            'returnurl' => $returnurl,
            'method'    => 'miniapp',
            'openid'    => $this->auth->openid
        ];

        $response = \addons\epay\library\Service::submitOrder($params);
        $response['order'] = $order;
        $this->success('查询成功', $response);
    }



    /**
     * 企业支付通知和回调
     */
    public function epay()
    {
        $type = $this->request->param('type');
        $paytype = $this->request->param('paytype');
        if ($type == 'notify') {
            $pay = \addons\epay\library\Service::checkNotify($paytype);
            if (!$pay) {
                echo '签名错误';
                return;
            }
            $data = $pay->verify();
            try {
                $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
                DeviceOrder::settle($data['out_trade_no'], $payamount);
            } catch (Exception $e) {
            }
            return $pay->success()->send();
        } else {
            $pay = \addons\epay\library\Service::checkReturn($paytype);
            if (!$pay) {
                $this->error('签名错误');
            }
            //微信支付没有返回链接
            if ($pay === true) {
                $this->success("请返回网站查看支付状态!", "");
            }

            //你可以在这里定义你的提示信息,但切记不可在此编写逻辑
            $this->success("恭喜你！充值成功!", url("user/index"));
        }
        return;
    }
}
